package filters;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 登陆过滤器.只过滤jsp页面
 * 
 * @author gj
 * 
 */
public class LoginFilter implements Filter {

	@Override
	public void destroy() {

	}

	@Override
	public void doFilter(ServletRequest servletrequest, ServletResponse servletresponse, FilterChain filterchain) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) servletrequest;
		HttpServletResponse response = (HttpServletResponse) servletresponse;
		HttpSession session = request.getSession();

		System.out.println("============doFilter============" + request.getRequestURI());

		if (request.getRequestURI().endsWith("login.jsp")) {
			filterchain.doFilter(servletrequest, servletresponse);
		} else {
			Object userInfo = session.getAttribute("user");
			if (userInfo == null) {
				String loginUrl = request.getContextPath() + "/login.jsp";
				response.getWriter().write("<script>window.parent.location.href = '" + loginUrl + "'</script>");
			} else {
				filterchain.doFilter(servletrequest, servletresponse);
			}
		}
	}

	@Override
	public void init(FilterConfig filterconfig) throws ServletException {

	}

}
